#!/usr/bin/env bash
# html-table-for -- Produce HTML table for given CSV or TSV file
# > html-table-for FILE
#
# Author: Jaeho Shin <netj@cs.stanford.edu>
# Created: 2015-02-08
set -eu

[[ $# -gt 0 ]] || usage "$0" "Missing FILE"

File=$1; shift

case $File in
*.tsv)
    # TODO handle TSV escapes?
    cat <<EOF
<table class="table table-stripped">
<thead><tr>
EOF
    head -1 "$File" | tr '\t' '\n' | sed 's:.*:<th>&</th>:'
    cat <<EOF
</tr></thead>
<tbody>
EOF
    tail -n +2 "$File" | sed 's:^:<tr><td>:; s:$:</td></tr>:; s:[	]:</td><td>:g'
    cat <<EOF
</tbody>
</table>
EOF
    ;;

*.csv) # TODO
    coffee -e '
    fs = require "fs"
    csv = require "csv"
    escape = require "escape-html"

    [filename] = process.argv[4..]

    parser = csv.parse {
        columns: yes
        header: yes
        auto_parse: yes
    }
    printed_thead = no
    print = (s) -> console.log s
    parser
        .on "readable", ->
            while row = parser.read()
                unless printed_thead
                    print """
                        <table class="table table-stripped">
                        <thead><tr>
                        #{("<th>#{escape column}</th>" for column of row).join "\n"}
                        </tr></thead>
                        <tbody>
                        """
                    printed_thead = yes
                print """
                    <tr>#{("<td>#{escape value}</td>" for column,value of row).join ""}</tr>
                    """
        .on "finish", ->
            print """
                </tbody>
                </table>
                """
        .on "error", ->
            console.error "Cannot parse CSV"
            process.exit 2
    input = (fs.createReadStream filename)
        .on "open", -> input.pipe parser
        .on "error", ->
            console.error "#{filename}: Cannot open file"
            process.exit 4
    ' "$File"
    ;;

*)
    error "$File: Unsupported data format"
esac
